package edu.mse.camel.client.eventbus.pubsub;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import edu.mse.camel.client.events.IEvent;

/*package*/ class EventCache {

	private List<IEvent> cache;
	
	/*package*/ EventCache() {
		this.cache = new ArrayList<IEvent>();
	}
	
	/*package*/ synchronized void cacheEvent(IEvent event) {
		cache.add(event);		
	}
	
	/**
	 * Returns all the events that were cached by the EventManager at the time of
	 * making the call. We guarantee that the order of sending out 
	 * events is the same as the order in which they came in
	 * 
	 * @return
	 */
	/*package*/ synchronized Iterator<IEvent> getCache() {
		List<IEvent> tempCache = new ArrayList<IEvent>();
		tempCache.addAll(cache);
		return tempCache.iterator();
	}
	
	/**
	 * This method has O(n^2) complexity because it has the simplest possible implementation.
	 * We have a simple implementation because we guarantee that the order of sending out 
	 * events is the same as the order in which they came in. For better
	 * performance use the getCache() method and ignore the events 
	 * you are not interested in.
	 * 
	 * @param events
	 * @return iterator for events with the given IDs
	 */
	/*package*/ synchronized Iterator<IEvent> getCache(List<String> eventIDs) {
		List<IEvent> tempCache = new ArrayList<IEvent>();
		for (String anID : eventIDs) {
			for (IEvent anEvent : cache) {
				if (anEvent.getEventID().equals(anID)) {
					tempCache.add(anEvent);
				}
			}
		}
		return tempCache.iterator();
	}

	/*package*/ synchronized void clearCache() {
		cache.clear();
	}
	
}
